package com.handa.admin.protocolLib.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.handa.admin.protocolLib.entity.DO.ProtocolItemDO;
import com.handa.admin.protocolLib.entity.DTO.ProtocolField;
import com.handa.admin.protocolLib.entity.DTO.ProtocolItemDTO;
import com.handa.admin.protocolLib.entity.QTO.ProtocolItemQTO;
import com.handa.admin.protocolLib.service.ProtocolItemService;
import com.handa.admin.userservice.common.entity.LoginUser;
import com.handa.admin.userservice.common.entity.Response;
import com.handa.admin.userservice.common.exception.ServiceException;
import com.handa.admin.userservice.common.utils.RequestContext;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;
import java.util.Objects;

@RestController
@RequestMapping("/Admin/protocolItem/")
@Slf4j
public class ProtocolItemController {

    @Resource
    private ProtocolItemService protocolItemService;

    @PostMapping("getAll")
    public Response<IPage<ProtocolItemDTO>> getAll(@RequestBody ProtocolItemQTO qto) {
        // 设置默认分页参数
        int pageNum = qto.getPageNum() == null ? 1 : qto.getPageNum();
        int pageSize = qto.getPageSize() == null ? 10 : qto.getPageSize();

        // 创建分页对象
        Page<ProtocolItemDO> page = new Page<>(pageNum, pageSize);

        // 构建查询条件
        QueryWrapper<ProtocolItemDO> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(qto.getProtocolName())) {
            queryWrapper.like("protocol_name", qto.getProtocolName()); // 注意数据库字段名可能是下划线格式
        }
        if (qto.getCreateTimeBegin() != null) {
            queryWrapper.ge("create_time", qto.getCreateTimeBegin());
        }
        if (qto.getCreateTimeEnd() != null) {
            queryWrapper.le("create_time", qto.getCreateTimeEnd());
        }

        if (StringUtils.isNotBlank(qto.getCreateNickName())) {
            queryWrapper.like("create_nick_name", qto.getCreateNickName());
        }
        if (qto.getCategories() != null && !CollectionUtils.isEmpty(qto.getCategories())) {
            queryWrapper.in("category", qto.getCategories());
        } else {
            // 非0 才进行条件查询，否则查所有
            if (qto.getCategory() != null && qto.getCategory() != 0) {
                queryWrapper.eq("category", qto.getCategory());
            }
        }

        if (qto.getMsgType() != null) {
            queryWrapper.eq("msg_type", qto.getMsgType());
        }

        if (qto.getCode() != null) {
            queryWrapper.eq("code", qto.getCode());
        }

        // 执行分页查询
        IPage<ProtocolItemDO> res = protocolItemService.page(page, queryWrapper);

        // 转换为 DTO 分页对象
        IPage<ProtocolItemDTO> res2 = res.convert(this::convertDO2DTO);

        return Response.success(res2);
    }

    @PostMapping("saveOrUpdate")
    public Response<ProtocolItemDTO> saveOrUpdate(@RequestBody ProtocolItemDTO dto) {

        if (StringUtils.isBlank(dto.getProtocolName())) {
            throw new ServiceException("协议名称不能为空");
        }
        if (dto.getCategory() == null) {
            throw new ServiceException("协议分类不能为空");
        }
        if (dto.getMsgType() == null) {
            throw new ServiceException("协议消息类型不能为空");
        }
        LoginUser loginUser = RequestContext.getLoginUser();
        if (Objects.isNull(loginUser)) {
            throw new ServiceException("当前登陆用户为空");
        }

        Date now = new Date();
        ProtocolItemDO itemDO = new ProtocolItemDO();

        itemDO.setProtocolName(dto.getProtocolName());
        itemDO.setMsgType(dto.getMsgType());

        if (dto.getCode() != null) {
            itemDO.setCode(dto.getCode());
        }

        itemDO.setUpdateUserId(loginUser.getUserId());
        itemDO.setUpdateUserName(loginUser.getUsername());
        itemDO.setUpdateNickName(loginUser.getNickname()); // 如果有昵称字段
        itemDO.setUpdateTime(now);
        itemDO.setCategory(dto.getCategory());


        // 转换 protocolContent 为 JSON 字符串
        if (dto.getProtocolContent() != null) {
            try {
                String protocolContentJson = JSON.toJSONString(dto.getProtocolContent());
                itemDO.setProtocolContent(protocolContentJson);
            } catch (Exception e) {
                throw new ServiceException("协议内容格式错误");
            }
        } else {
            throw new ServiceException("协议内容不能为空");
        }

        // 更改
        if (dto.getId() != null) {
            itemDO.setId(dto.getId());
            itemDO.setUpdateTime(now);

            itemDO.setCreateUserId(dto.getCreateUserId());
            itemDO.setCreateUserName(dto.getCreateUserName());
            itemDO.setCreateNickName(dto.getCreateNickName());
            itemDO.setCreateTime(dto.getCreateTime());

            protocolItemService.updateById(itemDO);
        }
        // 新增
        else {
            itemDO.setCreateUserId(loginUser.getUserId());
            itemDO.setCreateUserName(loginUser.getUsername());
            itemDO.setCreateNickName(loginUser.getNickname()); // 如果有昵称字段
            itemDO.setCreateTime(now);

            protocolItemService.save(itemDO);
        }

        return Response.success(convertDO2DTO(itemDO));
    }

    @GetMapping("getById")
    public Response<?> getById(@RequestParam String id) {
        ProtocolItemDO protocolItemDO = protocolItemService.getById(id);
        return Response.success(convertDO2DTO(protocolItemDO));
    }



    @PostMapping("deleteById")
    public Response<?> deleteById(@RequestBody ProtocolItemDTO qto) {
        // 构建查询条件
        QueryWrapper<ProtocolItemDO> queryWrapper = new QueryWrapper<>();
        if (qto.getId() == null) {
            throw new ServiceException("协议Id 不能为空");
        } else {
            queryWrapper.eq("id", qto.getId());
        }

        protocolItemService.remove(queryWrapper);

        return Response.success();
    }


    private ProtocolItemDTO convertDO2DTO(ProtocolItemDO protocolItemDO) {
        ProtocolItemDTO dto = new ProtocolItemDTO();
        // 复制基本属性
        dto.setId(protocolItemDO.getId());
        dto.setProtocolName(protocolItemDO.getProtocolName());
        if (protocolItemDO.getMsgType() != null) {
            dto.setMsgType(protocolItemDO.getMsgType());
        }
        if (protocolItemDO.getCode() != null) {
            dto.setCode(protocolItemDO.getCode());
        }

        dto.setCreateUserId(protocolItemDO.getCreateUserId());
        dto.setCreateUserName(protocolItemDO.getCreateUserName());
        dto.setCreateNickName(protocolItemDO.getCreateNickName());
        dto.setCreateTime(protocolItemDO.getCreateTime());

        dto.setUpdateUserId(protocolItemDO.getUpdateUserId());
        dto.setUpdateUserName(protocolItemDO.getUpdateUserName());
        dto.setUpdateNickName(protocolItemDO.getUpdateNickName());
        dto.setUpdateTime(protocolItemDO.getUpdateTime());

        // 转换 protocolContent
        if (StringUtils.isNotBlank(protocolItemDO.getProtocolContent())) {
            try {
                ProtocolField protocolField = JSON.parseObject(protocolItemDO.getProtocolContent(), ProtocolField.class);
                dto.setProtocolContent(protocolField);
            } catch (Exception e) {
                // 处理JSON解析异常
                dto.setProtocolContent(null);
            }
        }

        dto.setCategory(protocolItemDO.getCategory());

        return dto;
    }

}
